import Vector from './treeVector.js';
import Leaf from './treeLeaf.js';
var Branch = function (p, v, r, c, t) {
	this.p = p || null;

	this.v = v || null;

	this.r = r || 0;

	this.length = 0;

	this.generation = 1;

	this.tree = t || null;

	this.color = c || 'rgba(255,255,255,1.0)';

	this.register();
};

Branch.prototype = {
	register: function () {
		this.tree.addBranch(this);
	},

	draw: function () {
		var ctx = this.tree.ctx;

		ctx.beginPath();

		ctx.fillStyle = this.color;

		ctx.moveTo(this.p.x, this.p.y);

		ctx.arc(this.p.x, this.p.y, this.r, 0, Branch.circle, true);

		ctx.fill();
	},

	modify: function () {
		var angle = 0.18 - 0.1 / this.generation;

		this.p.add(this.v);

		this.length += this.v.length();

		this.r *= 0.99;

		this.v.rotate(Branch.random(-angle, angle)); //.mult(0.996);

		if (this.r < 0.8 || this.generation > 10) {
			this.tree.removeBranch(this);

			var l = new Leaf(this.p, 10, this.color, this.tree.ctx);

			l.render();
		}
	},

	grow: function () {
		this.draw();

		this.modify();

		this.fork();
	},

	fork: function () {
		var p = this.length - Branch.random(100, 200); // + (this.generation * 10);

		if (p > 0) {
			var n = Math.round(Branch.random(1, 3));

			this.tree.stat.fork += n - 1;

			for (var i = 0; i < n; i++) {
				Branch.clone(this);
			}

			this.tree.removeBranch(this);
		}
	},
};

Branch.circle = 2 * Math.PI;

Branch.random = function (min, max) {
	return Math.random() * (max - min) + min;
};

Branch.clone = function (b) {
	var r = new Branch(new Vector(b.p.x, b.p.y), new Vector(b.v.x, b.v.y), b.r, b.color, b.tree);

	r.generation = b.generation + 1;

	return r;
};

Branch.rgba = function (r, g, b, a) {
	return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
};

Branch.randomrgba = function (min, max, a) {
	return Branch.rgba(Math.round(Branch.random(min, max)), Math.round(Branch.random(min, max)), Math.round(Branch.random(min, max)), a);
};

export default Branch;
